//
//  LiftIMContactManger.m
//  AAIM
//
//  Created by awh on 2019/12/29.
//  Copyright © 2019年 AAIM. All rights reserved.
//

#import "LiftIMContactManger.h"

#import "NSDictionary+JSONString.h"

#import "ReceiveResultModel.h"
#import "BTMessageModel.h"

#import "IMClient.h"

@implementation LiftIMContactManger

#pragma mark - public

- (void)addDelegate:(id<LiftIMContactMangerDelegate>)delegate {
    NSValue *delegateValue = [NSValue valueWithNonretainedObject:delegate];
    if (![self.delegates containsObject:delegateValue]) {
        [self.delegates addObject:delegateValue];
    }
}

- (void)removeDelegate:(id<LiftIMContactMangerDelegate>)delegate {
    NSValue *delegateValue = [NSValue valueWithNonretainedObject:delegate];
    if ([self.delegates containsObject:delegateValue]) {
        [self.delegates removeObject:delegateValue];
    }
    
}

- (void)receivedMessages:(NSArray<BTMessageModel *> *)messages {
    [messages enumerateObjectsUsingBlock:^(BTMessageModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.messageDirection = MessageDirectionReceive;
    }];
    [self postNotifications:messages];
}


#pragma mark - 发送消息


#pragma mark - 私有方法

// 通知代理

- (void)postNotifications:(NSArray<BTMessageModel *> *)messages {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.delegates enumerateObjectsUsingBlock:^(NSValue *delegateValue, NSUInteger idx, BOOL * _Nonnull stop) {
            id<LiftIMContactMangerDelegate> delegate = delegateValue.nonretainedObjectValue;
            if ([delegate respondsToSelector:@selector(contactChangedMessageDidReceive:)]) {
                [delegate contactChangedMessageDidReceive:messages];
            }
        }];
    });
}

#pragma mark - getter

- (NSMutableArray *)delegates {
    if (!_delegates) {
        _delegates = [NSMutableArray new];
    }
    return _delegates;
}

@end

